package com.bw.common.mvi

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.launch

abstract class BaseFragment <V : ViewBinding,VM : BaseViewModel<*, *>> : Fragment() {

    protected lateinit var vm : VM
    abstract fun createVM():VM
    protected val inflate : LayoutInflater by lazy { LayoutInflater.from(context) }
    protected lateinit var v : V

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vm  = createVM()
        v = createViewBinding() as V
        initUIStateFlow()
        initView()
        bindState()
        initData()
        return v.root
    }

    abstract fun initView()

    abstract fun initData()

    abstract fun bindState()

    abstract fun createViewBinding():ViewBinding

    @SuppressLint("UnsafeRepeatOnLifecycleDetector")
    fun initUIStateFlow(){
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.requestStateFlow.collect{
                    if (it.request){
                        showDialog()
                    }else if (it.complate){
                        hideDialog()
                    }else if (it.erro){
                        showEmptyView()
                    }
                }
            }
        }
    }

    fun showDialog(){
        log("showDialog")
    }
    fun hideDialog(){
        log("hideDialog")
    }
    fun showEmptyView(){
        log("showEmptyView")
    }

    fun log(msg : String){
        Log.e("LIJIANG--",msg)
    }
}